/*******************************************************************************
 * Copyright (c) 2008, 2009 Fabio Mauro - Alberto Terraneo.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.2
 * or any later version published by the Free Software Foundation.
 *     
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Free Documentation License for more details.
 *     
 * You should have received a copy of the GNU Free Documentation 
 * License along with this distribution; if not, send a email to authors:
 * aterraneo <at> users.sourceforge.net
 * bigmoby09 <at> users.sourceforge.net
 *******************************************************************************/
package it.blueocean.acanto.web;

import it.blueocean.acanto.security.SpringSecurityLoginContext;
import it.blueocean.acanto.web.pages.secure.MasterPage;
import it.blueocean.acanto.web.platform.components.errorPages.BrowserNotSupportedErrorPage;
import it.blueocean.acanto.web.platform.components.errorPages.ExceptionCatcherPage;
import it.blueocean.acanto.web.platform.components.urls.NonVersionedHybridUrlCodingStrategy;
import it.blueocean.acanto.web.platform.login.LoginPage;

import java.net.MalformedURLException;

import org.apache.log4j.Logger;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.markup.html.pages.InternalErrorPage;
import org.apache.wicket.security.WaspApplication;
import org.apache.wicket.security.actions.ActionFactory;
import org.apache.wicket.security.hive.HiveMind;
import org.apache.wicket.security.hive.authentication.LoginContext;
import org.apache.wicket.security.hive.config.PolicyFileHiveFactory;
import org.apache.wicket.security.swarm.SwarmWebApplication;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.wicketstuff.htmlvalidator.HtmlValidationResponseFilter;

public abstract class AcantoPlatformApplication extends SwarmWebApplication implements WaspApplication
{
	private final static Logger logger = Logger.getLogger(AcantoPlatformApplication.class);
	
	private AuthenticationManager authenticationManager;
	
	private String configurationType;
	
	private String authorizationFile;

	@Override
	protected void init()
	{
		super.init();

		// THIS LINE IS IMPORTANT - IT INSTALLS THE COMPONENT INJECTOR THAT WILL
        // INJECT NEWLY CREATED COMPONENTS WITH THEIR SPRING DEPENDENCIES
        addComponentInstantiationListener(new SpringComponentInjector(this));

        mount(new NonVersionedHybridUrlCodingStrategy("login", LoginPage.class));
        mount(new NonVersionedHybridUrlCodingStrategy("home", MasterPage.class));
        mount(new NonVersionedHybridUrlCodingStrategy("browserNotSupportedErrorPage", BrowserNotSupportedErrorPage.class));
        mount(new NonVersionedHybridUrlCodingStrategy("exceptionCatcherPage", ExceptionCatcherPage.class));
        
		getRequestCycleSettings().setResponseRequestEncoding("UTF-8");

		if("development".equalsIgnoreCase(getConfigurationType()))
		{		    
//	TODO		getRequestCycleSettings().addResponseFilter(new HtmlValidationResponseFilter());
			getDebugSettings().setAjaxDebugModeEnabled(true);
		    getDebugSettings().setComponentUseCheck(true);
		    getDebugSettings().setLinePreciseReportingOnAddComponentEnabled(true);
		}
		else
		{
			// misc settings
			getMarkupSettings().setCompressWhitespace(true);
			getMarkupSettings().setStripComments(true);
			getMarkupSettings().setStripWicketTags(true);
		}

		getApplicationSettings().setInternalErrorPage(InternalErrorPage.class);
		getApplicationSettings().setPageExpiredErrorPage(LoginPage.class);
		getApplicationSettings().setAccessDeniedPage(LoginPage.class);
		
		logger.debug("Acanto started.");
	}

	@Override
	public Class<MasterPage> getHomePage()
	{
		return MasterPage.class;
	}
	
	@Override
	public Class<LoginPage> getLoginPage()
	{
		return LoginPage.class;
	}
	
	@Override
	protected Object getHiveKey()
	{
		//if you are using servlet api 2.5 i would suggest using:
        return getServletContext().getContextPath();
	}

	@Override
	protected void setUpHive()
	{
		ActionFactory actionFactory = getActionFactory();
		 //create factory
        PolicyFileHiveFactory policyFileHiveFactory = new PolicyFileHiveFactory(actionFactory);
        try
        {
            //this example uses 1 policy file but you can add as many as you like
        	policyFileHiveFactory.addPolicyFile(getServletContext().getResource(getAuthorizationFile()));
        }
        catch (MalformedURLException e)
        {
            throw new WicketRuntimeException(e);
        }
        //register factory
        HiveMind.registerHive(getHiveKey(), policyFileHiveFactory);
        //note we are not checking if a hive already exist because this app will only be deployed once
	}
	
	public final WebApplicationContext getSpringContext()
	{
		return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
	}
	
	public LoginContext getLogoffContext()
	{
		return new SpringSecurityLoginContext();
	}
	
	public String getConfigurationType()
	{
		return configurationType;
	}

	public void setConfigurationType(String configurationType)
	{
		this.configurationType = configurationType;
	}
	
	public void setAuthenticationManager(AuthenticationManager manager)
	{
		authenticationManager = manager;
	}

	public AuthenticationManager getAuthenticationManager()
	{
		return authenticationManager;
	}

	public String getAuthorizationFile()
	{
		return authorizationFile;
	}

	public void setAuthorizationFile(String authorizationFile)
	{
		this.authorizationFile = authorizationFile;
	}

}
